package com.LearnInWorld.oauth.controller;

import com.LearnInWorld.entity.Result;
import com.LearnInWorld.entity.StatusCode;
import com.LearnInWorld.oauth.service.OauthService;
import com.LearnInWorld.oauth.util.AuthToken;
import com.LearnInWorld.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/oauth")
public class OauthController {

    @Autowired
    private OauthService oauthService;
    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;

    @PostMapping("/login")
    public Result login(String username, String password, HttpServletResponse response) {
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不存在");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("密码不存在");
        }
        AuthToken authToken = oauthService.login(username, password, clientId, clientSecret);
        if (authToken == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败");
        }
        saveToken2Cookie(response, authToken.getJti());
        return new Result(true, StatusCode.OK, "登录成功", authToken.getJti());
    }

    private void saveToken2Cookie(HttpServletResponse response, String jti) {
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jti, cookieMaxAge, false);
    }

}
